<template>
  <div class="container">
    <van-popup round v-model="popupShow" position="bottom">
      <template v-if="popupState == 'picker'">
        <van-picker show-toolbar :columns="pickerData" @confirm="pickerConfirm" @cancel="pickerCancel" />
      </template>
      <template v-if="popupState == 'cascader'">
        <van-cascader :field-names="fieldNames" v-model="cascaderValue" title="请选择所属区域" :options="cascadeOptions"
          active-color="#D58913" @finish="cascaderFinish" @close="cascaderClose" />
      </template>
    </van-popup>

    <div class="container-inner">
      <van-form ref="form" scroll-to-error :show-error-message="false" @failed="onFailed" @submit="onSubmit">
        <div class="card">
          <div class="card-bar">
            <div class="card-bar-title">家长信息</div>
          </div>
          <div class="card-container">
            <van-field v-model="formData.name" required clearable maxlength="20"
              :rules="[{ required: true, message: '请检查姓名' }]" name="name" label="姓名" placeholder="请输入姓名">
            </van-field>
            <van-field v-model="formData.tel" required clearable maxlength="11" type="tel"
              :rules="[{ required: true, message: '请检查联系方式' }]" name="tel" label="联系方式" placeholder="请输入联系方式">
            </van-field>
            <van-field v-model="formData.card_no" required clearable readonly maxlength="18"
              :rules="[{ required: true, validator: cardNoValidator, message: '请检查身份证号' }]" name="card_no" label="身份证号"
              placeholder="请输入身份证号">
            </van-field>
            <van-field name="sex" required :rules="[{ required: true, message: '请检查性别' }]" label="性别">
              <template #input>
                <van-radio-group v-model="formData.sex" checked-color="#D58913" direction="horizontal">
                  <van-radio name="1">男</van-radio>
                  <van-radio name="2">女</van-radio>
                </van-radio-group>
              </template>
            </van-field>
            <van-field readonly clickable is-link name="relationship_name" :value="formData.relationship_name"
              label="亲属关系" placeholder="点击选择" @click="pickerChange('relationship')" required
              :rules="[{ required: true, message: '请检查亲属关系' }]">
            </van-field>
            <van-field readonly clickable is-link name="ascription" :value="formData.ascription" label="家庭所属区域"
              placeholder="点击选择" @click="pickerChange('ascription')" required
              :rules="[{ required: true, message: '请检查家庭所属区域' }]">
            </van-field>
            <van-field v-model="formData.quarter" required clearable maxlength="20"
              :rules="[{ required: true, message: '请检查家庭所属小区' }]" name="quarter" placeholder="请输入家庭所属小区">
            </van-field>
            <template>
              <div class="field-title">家庭所属小区</div>
              <div class="field-text">(或无则住宅楼名)</div>
            </template>
            <van-field v-model="formData.address" rows="3" autosize label="详细地址" type="textarea" maxlength="255"
              placeholder="请输入详细地址" required :rules="[{ required: true, message: '请检查详细地址' }]">
            </van-field>
          </div>
        </div>
      </van-form>
    </div>

    <div class="bottom-bar">
      <van-button class="bottom-bar-btn" block size="large" color="#D58913" type="info" text="确认提交"
        @click="submitAction" />
    </div>
  </div>
</template>

<script>
import { getSexByIdCard, identityCodeValid } from '@/libs/tools'
import { getDLAreaList, getDictList, getParentInfo, saveParentCohabitation } from '@/api/school.js'

export default {

  data() {
    return {
      route: {},
      userInfo: {},
      popupShow: false,
      popupState: '',
      pickerType: '',
      pickerData: [],
      userData: {},
      disabled: {},
      formData: {},
      cascaderShow: false,
      cascaderValue: '',
      cascadeOptions: [],
      fieldNames: {
        text: 'name',
        value: 'code',
        children: 'children'
      },
      dictData: {},
    }
  },

  props: {},

  components: {},

  computed: {},

  watch: {},

  mounted() {
    this.route = this.$route.query
    this.userInfo = this.$store.state.user.userInfo
    this.init()
  },

  methods: {
    async init() {
      // 获取区域所属
      const areaData = await getDLAreaList()
      if (areaData.data.errcode == 0) {
        let options = this.$common.xeUtils.toArrayTree(areaData.data.data, {
          strict: true,
          parentKey: 'parent_id',
          key: 'id',
          children: 'children'
        })
        this.cascadeOptions = options[0].children
      }
      // 获取字典信息
      const dictData = await getDictList({ key_name: 'text', key_code: 'value', type: 'relationship' })
      if (dictData.data.errcode == 0) this.dictData.relationship = dictData.data.data
      // 回显
      const info = await getParentInfo({ card_no: this.userInfo.card_no })
      if (info.data.errcode == '0') {
        // console.log('回显', info.data.data)
        this.$set(this.formData, 'name', info.data.data.name)
        this.$set(this.formData, 'tel', info.data.data.tel)
        this.$set(this.formData, 'card_no', info.data.data.card_no)
        this.$set(this.formData, 'sex', info.data.data.sex)
        this.$set(this.formData, 'relationship', info.data.data.relationship)
        this.$set(this.formData, 'area_code', info.data.data.area_code)
        this.$set(this.formData, 'area_name', info.data.data.area_name)
        this.$set(this.formData, 'street_code', info.data.data.street_code)
        this.$set(this.formData, 'street_name', info.data.data.street_name)
        this.$set(this.formData, 'community_code', info.data.data.community_code)
        this.$set(this.formData, 'community_name', info.data.data.community_name)
        this.$set(this, 'cascaderValue', info.data.data.community_code)
        if (info.data.data.area_name && info.data.data.street_name && info.data.data.community_name) {
          this.$set(this.formData, 'ascription', info.data.data.area_name
            + '/' + info.data.data.street_name
            + '/' + info.data.data.community_name)
        }
        if (this.formData.relationship) this.$set(this.formData, 'relationship_name', this.dictData.relationship.find(item => item.value == this.formData.relationship).text)
        this.$set(this.formData, 'quarter', info.data.data.quarter)
        this.$set(this.formData, 'address', info.data.data.address)
      }
      // 初始化表单信息
      this.$set(this.formData, 'card_no', this.userInfo.card_no)
      let sex = getSexByIdCard(this.formData.card_no)
      if (sex) this.$set(this.formData, 'sex', sex.code)
    },
    pickerChange(type) {
      this.pickerType = type
      switch (type) {
        case 'ascription':
          this.popupState = 'cascader'
          this.popupShow = true
          break
        case 'relationship':
          this.popupState = 'picker'
          this.pickerType = 'relationship'
          this.pickerData = this.dictData.relationship
          this.popupShow = true
          break
      }
    },
    pickerConfirm(e) {
      switch (this.pickerType) {
        case 'relationship':
          this.formData.relationship_name = e.text
          this.formData.relationship = e.value
          this.popupShow = false
          break
      }
    },
    pickerCancel(e) {
      switch (this.pickerType) {
        case 'relationship':
          this.formData.relationship_name = ''
          this.formData.relationship = ''
          this.popupShow = false
          break
      }
    },
    cascaderFinish({ value, selectedOptions, tabIndex }) {
      this.formData.ascription = selectedOptions[0].name + '/' + selectedOptions[1].name + '/' + selectedOptions[2].name
      this.formData.area_code = selectedOptions[0].code
      this.formData.street_code = selectedOptions[1].code
      this.formData.community_code = selectedOptions[2].code
      this.formData.area_name = selectedOptions[0].name
      this.formData.street_name = selectedOptions[1].name
      this.formData.community_name = selectedOptions[2].name
      this.popupShow = false
    },
    cascaderClose() {
      this.formData.ascription = ''
      this.formData.area_code = ''
      this.formData.street_code = ''
      this.formData.community_code = ''
      this.formData.area_name = ''
      this.formData.street_name = ''
      this.formData.community_name = ''
      this.popupShow = false
    },
    failNotice(msg) {
      this.$notify({ type: 'danger', message: msg })
    },
    onFailed(errorInfo) {
      this.failNotice(errorInfo.errors[0].message)
    },
    // 身份证校验
    cardNoValidator(val) {
      const reg = identityCodeValid(val)
      if (!reg.pass) return false
    },
    submitAction() {
      this.$refs.form.submit()
    },
    onSubmit() {
      // 校验
      // if (!this.formData.temp) {
      //   this.failNotice('请输入体温')
      //   return false
      // } else {
      //   if (!identityTemp(this.formData.temp)) {
      //     this.failNotice('请输入正确体温')
      //     return false
      //   }
      // }
      this.$dialog.confirm({
        title: '是否确认提交',
        message: '',
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        confirmButtonColor: '#D58913',
        beforeClose: async (action, done) => {
          if (action === 'confirm') {
            const param = { ...this.formData, id: this.route.parent_id }
            // console.log('最终提交信息', param)
            const insertData = await saveParentCohabitation(param)
            if (insertData.data.errcode == 0) {
              this.$toast('操作成功')
              if (this.route.parent_id) {
                setTimeout(() => {
                  location.reload()
                }, 500)
              } else {
                const info = await getParentInfo({ card_no: this.userInfo.card_no })
                if (info.data.errcode == 0) {
                  this.$router.push({
                    path: '/school/children-list',
                    query: { parent_id: info.data.data.id }
                  })
                } else {
                  this.$router.go(-1)
                }
              }
              done()
            } else {
              this.$toast(insertData.data.errmsg)
              done()
            }
          } else {
            done();
          }
        }
      }).catch(() => {
      })
    }
  }
}
</script>

<style lang="less" scoped>
.container /deep/ .van-checkbox {
  min-height: 30px;
}

.container /deep/ .van-field__label span {
  display: inline-block;
  padding-left: 5px;
  width: 80%;
  text-align-last: justify;
}

.container {
  background: #F2F7FB;
  width: 100%;
  height: 100vh;
  box-sizing: border-box;

  &-inner {
    padding: 20px;

    .card {
      background: inherit;

      &-container {
        border-radius: 10px;
        overflow: hidden;
        background-color: white;
        padding: 10px;
      }
    }
  }

  .bottom-bar {
    position: fixed;
    bottom: 0;
    width: 100%;
  }
}
</style>
